package com.weixing.mall.core.handler;

import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import lombok.extern.slf4j.Slf4j;

import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常拦截器
 *
 * @Author: kfc
 * @Description: <br/>
 * Date:Create in 2019/6/18 10:40
 * @Modified By:
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 全局异常拦截，统一返回信息，避免堆栈信息泄露
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception ex) {
        // 生成返回结果
        log.warn("系统异常，异常信息如下:", ex);
        if (ex instanceof NoHandlerFoundException || ex instanceof HttpRequestMethodNotSupportedException) {
            return ResultUtil.notFound();
        }
        return ResultUtil.exception();
    }

    /**
     * 方法描述: 自定义异常拦截
     * @Author Small
     * @param e
     * @Date 2020/1/10 15:53
     * @return com.weixing.mall.base.wrapper.Result
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public Result handleInvalidTokenException(BusinessException e) {
        return ResultUtil.error(e.getMessage());
    }

    /**
     * 方法描述: 自定义异常拦截
     * @Author Small
     * @param e
     * @Date 2020/1/10 15:53
     * @return com.weixing.mall.base.wrapper.Result
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public Result handleInvalidException(BindException e) {
        return ResultUtil.error(e.getFieldError().getDefaultMessage());
    }
}
